//
//  WebViewController2.swift
//  Reader
//
//  Created by home on 2019/10/15.
//  Copyright © 2019 codeguesser. All rights reserved.
//

import UIKit
import WebKit
class WebViewController2: UIViewController,WKNavigationDelegate,WKUIDelegate {

    var saveAction:(String)->Void = {_ in}
    var url:URL?
    @IBOutlet weak var webView: WKWebView!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        if let _url = url{
            webView.load(URLRequest(url: _url))
        }
        if #available(iOS 16.4, *){
            webView.isInspectable = true
        }
        webView.navigationDelegate = self
        webView.uiDelegate = self
        
        self.navigationItem.rightBarButtonItems = [UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(save)),UIBarButtonItem(image: UIImage(systemName: "chevron.backward"), style: .plain, target: self, action: #selector(goPrevious))]
    }
    
    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        
        let frameInfo = navigationAction.targetFrame;
        if (!(frameInfo?.isMainFrame ?? false)) {
            webView.load(navigationAction.request)
        }
        return nil
    }
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if (navigationAction.targetFrame == nil) {
            webView.load(navigationAction.request)
        }
        decisionHandler(.allow)
    }
    @objc func save()  {
        self.saveAction(self.webView.url?.absoluteString ?? "")
        self.navigationController?.popVC()
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    @objc func goPrevious() {
        if webView.canGoBack {
            webView.goBack()
        }else{
            self.goBack()
        }
    }
}
